/**
 * 定义RemoteControlController远程控制
 */
(function(window, angular, undefined){

	var RemoteControlController = angular.module('RemoteControlController', ['ui.router','itfreer','waterCommon','RemoveControlService']);
	/**
	 * 常规管理控制器
	 */
	RemoteControlController.controller('commonManagerController',function($NavService,$sce,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state,$formObject){
		$NavService.setSelectedTab("remoteControl.commonManager");
		
		$scope.obj = {stationType : "0"};
		
		$scope.waterType = getWaterType(); // 1表示地表水，0表示污染源
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.wwtpReportParm = data;
			$scope.mn =$scope.wwtpReportParm["MN"+$scope.stationType];
			$scope.stationId = data.STATION_ID;
			if($scope.mn == null){
				$scope.mn = $scope.wwtpReportParm.MN;
			}
			$scope.getStationInfo();
	    });
		
		$scope.getStationInfo = function(){
			var stationType = $("#StationType li.selected").attr("StationType");
			$waterDataCommon.getPageRows("/RemoteControl/getStationInfo.do","stationInfo",{"mn":$scope.mn},100,1,function(d){
				$scope.realTimeData = d.parmData;
			});
			$waterDataCommon.getPageRows("/RemoteControl/getDeviceOrderByStationId.do","deviceOrders",{"stationId":$scope.stationId,"mn":$scope.mn},100,1,function(d){
			});
		}
		
		// 如果一台设备有多个参数，用弹框的方式显示参数测量值
		$scope.devicePollWindows = function(pollList){
			$scope.devicePollData = [];
			for(var i = 0;i< pollList.length;i++){
				var poll = pollList[i].NAME;
				if($scope.realTimeData[poll]){
					$scope.devicePollData.push({
						POLLNAME:$scope.realTimeData[poll].POLLNAME,
						MEAS:$scope.realTimeData[poll].MEAS + $scope.realTimeData[poll].UNIT
					});
				}
			}
			$itfreer.openWindow("devicePollWindows");
		}
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		$scope.waterDataCommon = $waterDataCommon;
	});
	
	/**
	 * 远程控制控制器
	 */
	RemoteControlController.controller('remoteControlController',function($q,$NavService,$OrderService,$sce,$scope,$itfreer,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope){
		$NavService.setSelectedTab("remoteControl.remoteControl"); //设置导航栏选中状态
		$scope.obj = {stationType : "0"};
		$scope.sysModel = "1";
		$scope.waterType = getWaterType();  // 1表示地表水，0表示污染源
		//去掉视频延迟函数
		if($wdp.timeout){
			clearTimeout($wdp.timeout); 
		}
		// 界面上仪表信息
		$scope.paramsInfo = [
		                     {name:"氨氮",value:"2994.8"},
		                     {name:"COD",value:"70.5"},
		                     {name:"总磷",value:"17.2"}
		                     ];
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.mn =data.MN;
			$scope.stationId = data.STATION_ID;

			$scope.getStationInfo();
			$scope.httpData = $httpData;
			
			// 打开websocket，监听设备消息
			if($scope.mn != null && $scope.mn != ""){
				$waterDataCommon.listenServer("DeviceInfo/"+$scope.mn+"/all",$scope.onWebSocketMessage);
			}
	    });
		
		// 处理websocket传过来的数据
		$scope.onWebSocketMessage = function(data){
			 $scope.$apply(function(){
			
				 for(var key in data){
					var item = data[key];
					// 如果是命令状态则更新命令面板信息
					if(key === "orderStatus"){
						var qn = item.QN;
						var status = item.STATUS;
						
						// 如果返回的是工控机手动自动切换的命令结果
						if(qn == $scope.PcAutoQN){
							if(status == "1"){
								// 工控机模式设置切换中
								$scope.sysMExeStatus = '0';
								$scope.sysMOrderStatusText = "现场机已收到命令";
							}
							else if(status == "2"){
								// 工控机模式设置切换中
								$scope.sysMExeStatus = '0';
								$scope.sysMOrderStatusText = "命令执行中……";
								$scope.PcAutoQN = "";
							}
							return;
						}
						
						var pollItems = $scope.httpData.deviceOrders.data[0];
						pollItems["waterGetter"] = {'orderList':$scope.waterGetterOrderItems};
						for(var pollName in pollItems){
							var orderItems = pollItems[pollName].orderList;
							for(var i in orderItems){
								var order = orderItems[i];
								var orderName = order.S_DOMAINCAPTION;
								if(order.QN == qn){
									if(status == "1"){
										order.ORDER_STATUS = "1";
									}
									else if(status == "2"){
										order.ORDER_STATUS = "3";
										order.QN = "";//如果已经收到执行完毕的消息，则把命令编号置空，反之延后的消息覆盖
									}
								}
							}
						}
					}
					else if(key === "sysInfo"){
						// 如果是系统状态信息，则更新系统状态面板
						if($scope.sysModel != item[0].SYS_MODEL_OLD){
							// 设置系统模式
							$scope.sysModel = item[0].SYS_MODEL_OLD;
							// 把系统模式执行状态改成空闲
							$scope.sysMExeStatus = '2';
							$scope.PcAutoQN = "";
							$.messager.alert('系统提示',"系统模式切换。");
						}
					}
					else if(key === "realTimeData"){
						$scope.realTimeData = item;
					}
					else if(key === "deviceInfo"){
						for(key in item){
							if(item[key].status && $httpData.deviceOrders.data[0][key]){
								$httpData.deviceOrders.data[0][key].status = item[key].status;
							}
							if(item[key].process && $httpData.deviceOrders.data[0][key]){
								$httpData.deviceOrders.data[0][key].process = item[key].process;
							}
							if(item[key].error && $httpData.deviceOrders.data[0][key]){
								$httpData.deviceOrders.data[0][key].error = item[key].error;
							}
						}
					}
				}
			 });
		}
		
		//获取站点信息
		$scope.getStationInfo = function(){
			$waterDataCommon.getPageRows("/RemoteControl/getStationInfo.do","stationInfo",{"stationId":$scope.stationId,"mn":$scope.mn},100,1,function(d){
				$scope.realTimeData = d.parmData;
				if(d&&d.mnInfo && d.mnInfo.data.length > 0){
					// 工控机当前状态
					$scope.sysModel = d.mnInfo.data[0].SYS_MODEL_OLD;
					// 工控机模式是否在改变中，2表示否
					$scope.sysMExeStatus = '2';
					$scope.sysMOrderStatusText = "系统模式切换中……";
				}
			});
			
			$waterDataCommon.getPageRows("/RemoteControl/getDeviceOrderByStationId.do","deviceOrders",{"stationId":$scope.stationId,"mn":$scope.mn},100,1,function(d){
				$scope.result= d;
				
			});
			$waterDataCommon.getPageRows("/RemoteControl/queryDeviceStatusByStationId.do","deviceStatus",{"stationId":$scope.stationId,"mn":$scope.mn},100,1,function(d){
				$scope.NH4_STATUS=$httpData.deviceStatus;
			});
		}
		
		$scope.waterGetterOrderItems = [
			                               {
			                            	   ORDER_CODE:"SYS_CY_PT",
			                            	   ORDER_ENABLE:"TRUE",
			                            	   ORDER_DESC:"采样",
			                            	   ORDER_STATUS:"2"
			                               },
			                               {
			                            	   ORDER_CODE:"SYS_PF_PT",
			                            	   ORDER_ENABLE:"TRUE",
			                            	   ORDER_DESC:"放样",
			                            	   ORDER_STATUS:"2"
			                               }
			     ];
		
		$scope.devicePollWindows = function(pollList){
			$scope.devicePollData = [];
			for(var i = 0;i< pollList.length;i++){
				var poll = pollList[i].NAME;
				if($scope.realTimeData[poll]){
					$scope.devicePollData.push({
						POLLNAME:$scope.realTimeData[poll].POLLNAME,
						MEAS:$scope.realTimeData[poll].MEAS + $scope.realTimeData[poll].UNIT
					});
				}
			}
			$itfreer.openWindow("devicePollWindows");
		}
		
		// 设置工控机手动和自动模式
		$scope.sendPcAutoOrder = function(value){
			var defered = $q.defer();
			$.messager.confirm("确认","确定要执行命令吗？",function(r){
				if(r){
					defered.resolve();
				}
			});
			
			defered.promise.then(function(){
				var orderStr = "";
				var mn = $scope.mn;// 工控机id
				orderStr += "Attr=SYS_MODEL,Value="+value;
				$scope.sysMOrderStatusText = "命令发送中……";
				$scope.sysMExeStatus = "1";
				$OrderService.sendOrder(mn,orderStr,null,function(d){
					$scope.PcAutoQN = d[0];
				});
			});
		}
		
		// 发送参数仪器单个命令
		$scope.sendSingleOrder = function(orderItem,orders,value){
			var defered = $q.defer();
			$.messager.confirm("确认","确定要执行命令吗？",function(r){
				if(r){
					defered.resolve();
				}
			});
			
			defered.promise.then(function(){
				var orderStr = "";
				var pollId = orderItem.PARMNAME; // 参数id
				var attr = orderItem.ORDER_CODE; // 命令
				var deviceId = orderItem.DEVICEID; // 设备id
				var mn = $scope.mn;// 工控机id
				if(pollId){
					orderStr += "PolID="+pollId+",";
				}
				orderStr += "Attr="+attr+",Value="+value;
				orderItem.ORDER_STATUS = "0";
				
				for(var i=0;i<orders.length;i++){
					var order = orders[i];
					order.ORDER_ENABLE = "FALSE";
				}
				$OrderService.sendOrder(mn,orderStr,deviceId,function(d){
					$scope.QN = d[0];
					orderItem.QN = $scope.QN;
				});
			});
		}
		
		$scope.maskClick = function(){
			$.messager.alert('系统提示',"请先进去远程手动模式");
		}
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		$scope.waterDataCommon = $waterDataCommon;
	});	
	
	/**
	 * 质控管理
	 */
	RemoteControlController.controller('EmergencyAndExceptionController',function($q,$NavService,$OrderService,$scope,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope){
		$NavService.setSelectedTab("remoteControl.emergencyAndException");
		$scope.waterType = getWaterType();  // 1表示地表水，0表示污染源
		
		//周期下拉数据
		$scope.periodSelect = [{"id":"1.0","text":"1次流程周期"},
		                       {"id":"2.0","text":"2次流程周期"},
		                       {"id":"5.0","text":"5次流程周期"},
		                       {"id":"4.0","text":"4次流程周期"},
		                       {"id":"10.0","text":"10次流程周期"},
		                       {"id":"20.0","text":"20次流程周期"},
		                       {"id":"30.0","text":"30次流程周期"},
		                       {"id":"50.0","text":"50次流程周期"},
		                       {"id":"100.0","text":"100次流程周期"},
		                       {"id":"150.0","text":"150次流程周期"},
		                       {"id":"250.0","text":"250次流程周期"},
		                       {"id":"0.0","text":"关闭"}
		                       ];

		//异常数据判别下拉
		$scope.orderList = [{"id":"1.0","text":"自动校准"},
		                       {"id":"2.0","text":"自动标样核查"},
		                       {"id":"3.0","text":"平行样测试"},
		                       {"id":"4.0","text":"加标回收"}];
		
		//加密周期下拉数据
		$scope.encryCycleList = [{"id":"1.0","text":"1小时"},
		                       {"id":"2.0","text":"2小时"},
		                       {"id":"3.0","text":"3小时"},
		                       {"id":"4.0","text":"4小时"}];
		
		$scope.onoff = [{"id":"1.0","text":"启用"},{"id":"0.0","text":"停用"}];
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.mn =data.MN;
			$scope.stationId = data.STATION_ID;

			$scope.getDevices();
	    });
		
		$("#StationType li").bind("click",function(){
			$("#StationType li").removeClass("selected");
			$(this).addClass("selected");
			$scope.getDevices();
		});

		// 获取站点的设备列表，远程控制是针对设备来控制
		$scope.getDevices = function(){
			$waterDataCommon.getPageRows("/RemoteControl/getStationDevices.do","devices",{"stationId":$scope.stationId},100,1);
		}
		
		// 保存常规质控管理配置
		$scope.commom = function(){
			var pollName = $scope.commomPoll;
			
			var mn = $scope.mn;// 工控机id
			var orderStr = "";
			if($scope.CALIB_Cycle){				
				if($scope.CALIB_Cycle == '0.0'){
					orderStr += "PolID="+pollName+",Attr=CALIB_MEAS,Value=0;";
				}
				else{
					orderStr += "PolID="+pollName+",Attr=CALIB_MEAS,Value=1;";
					orderStr += "PolID="+pollName+",Attr=CALIB_Cycle,Value="+$scope.CALIB_Cycle+";";
				}
			}
			if($scope.BYHC_Cycle){
				if($scope.BYHC_Cycle == '0.0'){
					orderStr += "PolID="+pollName+",Attr=BYHC_MEAS,Value=0;";
				}
				else{
					orderStr += "PolID="+pollName+",Attr=BYHC_MEAS,Value=1;";
					orderStr += "PolID="+pollName+",Attr=BYHC_Cycle,Value="+$scope.BYHC_Cycle+";";
				}
			}
			if($scope.JBHX_Cycle){
				if($scope.JBHX_Cycle == '0.0'){
					orderStr += "PolID="+pollName+",Attr=JBHX_MEAS,Value=0;";
				}
				else{
					orderStr += "PolID="+pollName+",Attr=JBHX_MEAS,Value=1;";
					orderStr += "PolID="+pollName+",Attr=JBHX_Cycle,Value="+$scope.JBHX_Cycle+";";
				}
			}
			if($scope.PXY_Cycle){
				if($scope.PXY_Cycle == '0.0'){
					orderStr += "PolID="+pollName+",Attr=PXY_MEAS,Value=0;";
				}
				else{
					orderStr += "PolID="+pollName+",Attr=PXY_MEAS,Value=1;";
					orderStr += "PolID="+pollName+",Attr=PXY_Cycle,Value="+$scope.PXY_Cycle+";";
				}
			}
			
			sendOrder(mn,orderStr);
		}
		
		$scope.isEndStep = function(){
			if($scope.STEP1 == "4.0"){
				$scope.selectEnable = "true";
			}
			if($scope.STEP2 == "4.0"){
				$scope.selectEnable = "true";
				$scope.step4_div_hide = "false";
			}
			if($scope.STEP3 == "4.0"){
				$scope.selectEnable = "false";
			}
		} 
		
		$scope.ycpd = function(){
			var pollName = $scope.autoEXCPoll;
			var mn = $scope.mn;
			var orderStr = "";
			
			if($scope.YCPD_MODE == "0.0"){
				orderStr += "PolID="+pollName+",Attr=YCPD_MODE,Value=0;";
			}
			else{
				orderStr += "PolID="+pollName+",Attr=YCPD_MODE,Value=1;";
				if($scope.STEP1){
					orderStr += "PolID="+pollName+",Attr=YCPD_STEP1,Value="+$scope.STEP1+";";
				}
				if($scope.STEP2){
					orderStr += "PolID="+pollName+",Attr=YCPD_STEP2,Value="+$scope.STEP2+";";
				}
				if($scope.STEP3){
					orderStr += "PolID="+pollName+",Attr=YCPD_STEP3,Value="+$scope.STEP3+";";
				}
				if($scope.STEP4){
					orderStr += "PolID="+pollName+",Attr=YCPD_STEP4,Value="+$scope.STEP4+";";
				}
				orderStr += "PolID="+pollName+",Attr=VALUE_HI,Value="+$scope.VALUE_HI+";";
				orderStr += "PolID="+pollName+",Attr=VALUE_LI,Value="+$scope.VALUE_LI+";";
			}
			sendOrder(mn,orderStr);
		}
		
		$scope.CBJM = function(){
			var pollName = $scope.cbjmPoll;
			
			var mn = $scope.mn;// 工控机id
			var orderStr = "";
			
			if($scope.CBJM_MODE == "0.0"){
				orderStr += "PolID="+pollName+",Attr=CBJM_MODE,Value=0;";
			}
			else{
				orderStr += "PolID="+pollName+",Attr=CBJM_MODE,Value=1;";
				orderStr += "Attr=YB_CBJM_Cycle,Value="+$scope.CBJM_Cycle+";";
				orderStr += "Attr=YB_CBJM_Number,Value="+$scope.CBJM_Number+";";
			}
			
			sendOrder(mn,orderStr);
		}
		
		$scope.set = function(){
			var pollName = $scope.setPoll;
			var mn = $scope.mn;// 工控机id
			var orderStr = "";
			
			orderStr += "PolID="+pollName+",Attr=PXY_WX_SET,Value="+$scope.PXY_WX_SET+";";
			orderStr += "PolID="+pollName+",Attr=BYHC_WX_SET,Value="+$scope.BYHC_WX_SET+";";
			orderStr += "PolID="+pollName+",Attr=JBHX_WX_SET,Value="+$scope.JBHX_WX_SET+";";
			orderStr += "PolID="+pollName+",Attr=ZKY_ND,Value="+$scope.ZKY_ND+";";
			sendOrder(mn,orderStr);
		}
		
		/**
		 * 获取对应参数的配置信息
		 */
		$scope.getQualityConfig = function(pollName){
			var mn = $scope.mn;
			$waterDataCommon.getPageRows("/RemoteControl/getQualityConfig.do","qualityConfig",{"mn":mn,"pollName":pollName},1,1,function(data){
				// 常规
				if( data[pollName+"_PXY_MEAS"] == '0.0'){
					$scope.CALIB_Cycle = '0.0'
				}
				else{
					$scope.CALIB_Cycle = data[pollName+"_CALIB_Cycle"];
				}
				if( data[pollName+"_BYHC_MEAS"] == '0.0'){
					$scope.BYHC_Cycle = '0.0';
				}
				else{
					$scope.BYHC_Cycle = data[pollName+"_BYHC_Cycle"];
				}
				
				if( data[pollName+"_JBHX_MEAS"] == '0.0'){
					$scope.JBHX_Cycle = '0.0';
				}
				else{
					$scope.JBHX_Cycle = data[pollName+"_JBHX_Cycle"];
				}
				if( data[pollName+"_PXY_MEAS"] == '0.0'){
					$scope.PXY_Cycle = '0.0';
				}
				else{
					$scope.PXY_Cycle = data[pollName+"_PXY_Cycle"];
				}
				// 超标加密
				$scope.VALUE_LI = data[pollName+"_VALUE_LI"];
				$scope.VALUE_HI = data[pollName+"_VALUE_HI"];
				$scope.YCPD_MODE = data[pollName+"_YCPD_MODE"];
				$scope.STEP1 = data[pollName+"_YCPD_STEP1"];
				$scope.STEP2 = data[pollName+"_YCPD_STEP2"];
				$scope.STEP3 = data[pollName+"_YCPD_STEP3"];
				$scope.STEP4 = data[pollName+"_YCPD_STEP4"];
				//质控配置
				$scope.PXY_WX_SET = data[pollName+"_PXY_WX_SET"];
				$scope.BYHC_WX_SET = data[pollName+"_BYHC_WX_SET"];
				$scope.JBHX_WX_SET = data[pollName+"_JBHX_WX_SET"];
				$scope.ZKY_ND = data[pollName+"_ZKY_ND"];
				// 加密
				$scope.CBJM_MODE = data[pollName+"_CBJM_MODE"];
				$scope.CBJM_Number = data["YB_CBJM_Number"];
				$scope.CBJM_Cycle = data["YB_CBJM_Cycle"];
			});
		}
		
		// 发送命令公共方法
		function sendOrder(mn,orders){
			var defered = $q.defer();
			$.messager.confirm("确认","确定要执行命令吗？",function(r){
				if(r){
					defered.resolve();
				}
			});
			
			defered.promise.then(function(){
				$OrderService.sendOrder(mn,orders,null,function(d){
					
				});
			});
		}
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		$scope.waterDataCommon = $waterDataCommon;
	});	
	
	/**
	 * 系统日志
	 */
	RemoteControlController.controller('sysLogController',function($NavService,$sce,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state,$formObject){
		$NavService.setSelectedTab("remoteControl.log");
		$scope.waterType = getWaterType();  // 1表示地表水，0表示污染源
		var now = new Date();
		$scope.startDate = getOracleDateString(new Date(Date.parse(now) + (86400000 * -30)));
		$scope.endDate = getOracleDateString(new Date(Date.parse(now) + (86400000 * 2)));
		
		$scope.obj = {stationType : "0"};
		
		$scope.$on('dataPramChanged', function(event, data) {
			$scope.mn =data.MN;
			$scope.stationId = data.STATION_ID;

			$scope.getLog();
	    });
		//时间验证
		$scope.checkErr = function(){		   
		    if((new Date($scope.startDate.replace(/-/g,"\/"))) > (new Date($scope.endDate.replace(/-/g,"\/")))){
		    	$.messager.alert("提示","起始时间不能大于结束时间");
		      return false;
		    }		 
		  };
		$("#StationType li").bind("click",function(){
			$("#StationType li").removeClass("selected");
			$(this).addClass("selected");
			$scope.getLog();
		});
		
		$("#logType li[tag]").bind("click",function(){
			var logType = $(this).attr("tag");
			$("#logType li[tag]").removeClass("selected");
			$(this).addClass("selected");
			$("#logContant div[tag]").hide();
			$("#logContant div[tag='"+logType+"']").show();
		});
		$scope.param="false";
		$scope.CancelParam=function(){
			$scope.param="false";
		}
		$scope.GetParam=function(){
			$scope.param="true";
		}
		$scope.getLog = function(){
			if($scope.checkErr()==false){
				return false;
			}
			var stationType = $("#StationType li.selected").attr("StationType");
			$waterDataCommon.getPageRows("/RemoteControl/getControlLog.do","controlLog",{"mn":$scope.mn,"startDate":$scope.startDate,"endDate":$scope.endDate},15,1,function(d){
				if(d == null || d==""){
					return;
				}
				if(d.data == null){
					return;
				}
				for(var i=0;i<d.data.length;i++){
					if(d.data[i].STATUS == '0'){
						d.data[i].STATUS = '未处理';
					}
					else if(d.data[i].STATUS == '1'){
						d.data[i].STATUS = '执行中';
					}
					else if(d.data[i].STATUS == '2'){
						d.data[i].STATUS = '执行完毕';
					}
					
					if(d.data[i].RESULT == '0'){
						d.data[i].RESULT = '无';
					}
					else if(d.data[i].RESULT == '1'){
						d.data[i].RESULT = '成功';
					}
					else if(d.data[i].RESULT == '2'){
						d.data[i].RESULT = '客户端不支持该命令';
					}
					else if(d.data[i].RESULT == '3'){
						d.data[i].RESULT = '读取OPC变量失败';
					}
				}
			});
			$waterDataCommon.getPageRows("/RemoteControl/getOnlineLog.do","onlineLog",{"mn":$scope.mn,"startDate":$scope.startDate,"endDate":$scope.endDate},15,1);
			$waterDataCommon.getPageRows("/RemoteControl/getQualityLog.do","getQualityLog",{"mn":$scope.mn,"startDate":$scope.startDate,"endDate":$scope.endDate,"parmName":$scope.parmName},15,1);
		}
		
		if($wdp.stationListReady == "true"){
			$scope.$emit('askDataPramChange', $scope.reportParms); 
		}
		
		function getOracleDateString(dtTmp){ 
			return dtTmp.getFullYear()+"-"+(dtTmp.getMonth()+1)+"-"+dtTmp.getDate();
		} 
		
		$scope.waterDataCommon = $waterDataCommon;
	});	
}(window, angular));